package com.dreamchaser.util;

import com.dreamchaser.domain.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取文件工具类
 */
public class FileUtil {
    /**
     * 读取txt文件内容
     * @param path 文件路径
     * @return List<String> txt文件内容封装成一个list返回,如果文件不存在就返回null
     */
    public static List<String> readTxtFile(String path){
        File file=new File(path);
        List<String> list=new ArrayList<>();
        if (file.exists()&&file.isFile()){
            BufferedReader reader=null;
            try {
                reader=new BufferedReader(new FileReader(file));
                String line=null;
                while ((line=reader.readLine())!=null){
                    list.add(line);
                }

                return list;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    //最后将输入流关闭
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }

    public static boolean writeFile(List<Book> list,String path){
        File file=new File(path);
        if (file.exists()&&file.isFile()){
            BufferedWriter bufferedWriter=null;
            try {
                bufferedWriter=new BufferedWriter(new FileWriter(file));
                for (Book book:list){
                    bufferedWriter.write(book.getId()+"    ");
                    bufferedWriter.write(book.getTitle()+"    ");
                    bufferedWriter.write(book.getName()+"    ");
                    bufferedWriter.write(book.getPublisher()+"    ");
                    bufferedWriter.write(book.getTime()+"    ");
                    bufferedWriter.write(book.getPrice()+"    ");
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                }
                return  true;
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return false;
    }
}
